/*
 * Copyright (c) 2020-2022. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.depsea.log.notification;

import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.depsea.log.notification.link.Link;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Wang Chengwei
 * @since 1.0.0 [2022/12/3 8:56]
 */
@Slf4j
public class DingtalkExceptionNotification extends AbstractExceptionNotification {
    private final DingTalkClient dingTalkClient;

    private final List<Link> links = new ArrayList<>();

    public DingtalkExceptionNotification(DingTalkClient dingTalkClient, List<Link> links) {
        this.dingTalkClient = dingTalkClient;
        if (links != null) {
            this.links.addAll(links);
        }
    }

    @Override
    protected void sendMessage(Message message) {
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setTimestamp(System.currentTimeMillis());
        request.setMsgtype("actionCard");

        OapiRobotSendRequest.Actioncard actionCard = new OapiRobotSendRequest.Actioncard();
        actionCard.setTitle(message.getTitle());
        actionCard.setText(message.toMarkdownMessage());
        actionCard.setBtnOrientation("1");

        List<OapiRobotSendRequest.Btns> btnList = new ArrayList<>();
        for (Link link : links) {
            OapiRobotSendRequest.Btns btn = new OapiRobotSendRequest.Btns();
            btn.setTitle(link.getLinkName());
            btn.setActionURL(link.getLinkUrl(message));
            btnList.add(btn);
        }
        actionCard.setBtns(btnList);

        request.setActionCard(actionCard);

        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setIsAtAll(true);

        request.setAt(at);

        try {
            OapiRobotSendResponse response = this.dingTalkClient.execute(request);
            if (response.isSuccess()) {
                log.info("请求失败，已发送钉钉通知消息");
            } else {
                log.error("错误编码：{}，错误信息：{}", response.getErrcode(), response.getErrmsg());
            }
        } catch (ApiException e) {
            log.error("发送钉钉消息通知失败：{}", e.getMessage(), e );
        }
    }

}

// 设备ID/编码         所属仓库          所属库区
